package com.xinzhi.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinzhi.domain.Man;
import com.xinzhi.domain.User;
import com.xinzhi.domain.UserRole;
import com.xinzhi.domain.vo.LoginUserVo;
import com.xinzhi.mapper.UserRoleMapper;
import com.xinzhi.service.LoginService;
import com.xinzhi.utils.Result;
import com.xinzhi.mapper.ManMapper;
import com.xinzhi.service.UserService;
import com.xinzhi.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.xinzhi.utils.SMSUtil;

import javax.servlet.http.HttpServletRequest;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    UserMapper userMapper;
    @Autowired
    ManMapper manMapper;
    @Autowired
   private LoginService loginService;
    @Autowired
    UserRoleMapper userRoleMapper;

    public static HashMap<String,Integer> hashCode= new HashMap<>();

    private static  final String salt ="123456";

    @Override
    public Result getInfo(int id) {
        User user = userMapper.selectById(id);
        if (user != null){
            Map<String,String> tokenMap = new HashMap<>();
            tokenMap.put("tname",user.getTname());
            tokenMap.put("headhost",user.getHeadshot());
            tokenMap.put("balance",""+user.getBalance());
            return Result.ok(tokenMap);
        }
        return Result.error(5003,"用户信息不存在");
    }

    @Override
    public Result uptname(String tname, int id) {
        if (tname == null){
            return Result.error(5008,"输入不能为空");
        }else {
            User user = new User();
            user.setUserId(id);
            user.setTname(tname);
            int count = userMapper.updateById(user);
            if (count > 0) {
                return Result.ok(tname);
            }
            return Result.error(5004, "修改失败");
        }
    }

    @Override
    public Result upheadshot(String headshot, int id) {
        if (headshot == null){
            return Result.error(5008,"输入不能为空");
        }
        User user = new User();
        user.setUserId(id);
        user.setHeadshot(headshot);
        int count = userMapper.updateById(user);
        if (count > 0){
            return Result.ok(headshot);
        }
        return Result.error(5004,"修改失败");
    }

    @Override
    public Result recharge(int id,BigDecimal money) {
        //判断用户输入充值金额大于0
        if (money.compareTo(BigDecimal.ZERO) == 1){
            //查询用户余额
            BigDecimal balance = userMapper.selectById(id).getBalance();
            //将用户充值金额与余额相加存入数据库中
            User user = new User();
            user.setUserId(id);
            user.setBalance(money.add(balance));
            int count = userMapper.updateById(user);
            if (count > 0){
                return Result.ok(money.add(balance));
            } else {
                return Result.error(5005,"修改失败");
            }
        }
        return Result.error(5005,"充值金额需要大于0");
    }

    @Override
    public Result inMan(Integer userid, String name, String phone) {
        if (name == null || name.equals("")){
            return Result.error(5008,"用户名输入不能为空");
        }else if (phone == null || phone.equals("")){
            return Result.error(5008,"电话输入不能为空");
        }

        int count = manMapper.inMan(userid,name,phone);
        if (count > 0){
            Map<String,String> tokenMap = new HashMap<>();
            tokenMap.put("name",name);
            tokenMap.put("phone",phone);
            return Result.ok(tokenMap);
        }
        return Result.error(5004,"添加失败");
    }

    @Override
    public Result getMan(Integer id) {
        List<Man> list = manMapper.getMan(id);
        if (list.size() >= 0){
            return Result.ok(list);
        }
        return Result.error(5005,"系统错误");
    }

    @Override
    public Result deMan(Integer id) {
        int count = manMapper.deMan(id);
        if (count > 0){
            return Result.ok(id);
        }
        return Result.error(5006,"删除失败");
    }

    @Override
    public Result upMan(Integer id, String name, String phone) {
        if (name == null || phone == null){
            return Result.error(5008,"输入不能为空");
        }
        int count = manMapper.upMan(id,name,phone);
        if (count > 0){
            Map<String,String> tokenMap = new HashMap<>();
            tokenMap.put("id",id+"");
            tokenMap.put("name",name);
            tokenMap.put("phone",phone);
            return Result.ok(tokenMap);
        }
        return Result.error(5004,"修改失败");
    }

    @Override
    public Result saveUser(User user) {
        List<User> selectbyname = userMapper.selectbyname(user.getUsername());
        if (selectbyname.size() > 0) {
            return Result.error(500,"用户名重复");
        }
        user.setPassword(DigestUtil.md5Hex(user.getPassword() + salt));
//        user.setUsername(username);
        int count = userMapper.saveUser(user);
        if (count > 0) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(2);
            List<User> id = userMapper.selectbyname(user.getUsername());
            userRole.setUserId(id.get(0).getUserId());
            userRoleMapper.insert(userRole);
            return Result.ok(count);
        }
        return Result.error(5003,"系统出错");
    }
    @Override
    public Result send(String tel, HttpServletRequest request) throws Exception {
        if(tel!=null){
            Random a= new Random();
            int num = (int) ((Math.random() * 9 + 1) * 100000);
            System.out.println(num);
            hashCode.put(tel,num);
            SMSUtil.sendSms(tel, num+"");
            return Result.ok(num);}
        return Result.error(500,"发送失败");

    }

    @Override
    public Result telReg(User user) {
//        User user = userMapper.selectUserByTel(tel);
//        if (null==user){
//            return Result.error(500,"手机号已被注册");
//        }
//            Integer integer = hashCode.get(tel);
//            if (integer == null){
//                return Result.error(500,"球球你去发个验证码");
//            }
//            System.out.println(integer);
//            if(integer.toString().equals(code)){
//                Random a= new Random();
//        int num =(int) ((Math.random() * 9 + 1) * 100000);;
//        String username = ""+num;
        if (user.getUsername() == null){
            return Result.error("用户名不能为空");
        }
        else
        if (user.getPassword() == null){
            return Result.error("密码不能为空");}
        else {
            List<User> selectbyname = userMapper.selectbyname(user.getUsername());
            if (selectbyname.size() > 0) {
                return Result.error(500,"用户名重复");
            }
            user.setPassword(DigestUtil.md5Hex(user.getPassword() + salt));
//        user.setUsername(username);
            int i = userMapper.insertByPhone(user);
            if (i > 0) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(2);
                List<User> id = userMapper.selectbyname(user.getUsername());
                userRole.setUserId(id.get(0).getUserId());
                userRoleMapper.insert(userRole);
                return Result.ok(i);
            } else {
//                    return Result.error(500,"验证码失败");
//            }
                return Result.error(500, "验证码失败");
            }
        }
    }

    @Override
    public User findUser(String username, String password) {


        LambdaQueryWrapper<User> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        queryWrapper.eq(User::getPassword,password);
        queryWrapper.select(User::getUsername,User::getUserId);
        queryWrapper.last("limit 1");
        return userMapper.selectOne(queryWrapper);

    }

    @Override
    public Result findUserByToken(String token) {
        /**
         * 1.token的合法性校验，是否为空，解析是否成功 redis 是否存在
         * 2.如何校验失败，返回错误
         * 3.如果成功返回对应的结果 LoginUserVo
         */

        User User = loginService.checkToken(token);
        if (User == null){
            return  Result.error(10041,"token不不合法");
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(User.getUserId());
        loginUserVo.setTname(User.getTname());
        loginUserVo.setUsername(User.getUsername());

        return Result.ok(loginUserVo);
    }


}




